<template>
  <el-drawer :title="title" :visible.sync="visible" direction="rtl" size="25%" :wrapperClosable="false" @close="close" >
    <div class="app-container">
      <!-- 操作按钮区域 -->
      <el-row class="mb8" style="margin-top: -20px;">
        <el-button type="primary" icon="el-icon-refresh"  @click="loadData()" :loading="loading">刷新</el-button>
        <span style="margin-left: 20px;"><el-checkbox @change="checkAll">全选</el-checkbox></span>
      </el-row>
      <div class="menu-tree">
        <div :style="treeStyle">
          <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" :default-expanded-keys="expandedKeys" check-strictly
              :default-checked-keys="checkedKeys"  @check="onCheck" :auto-expand-parent="autoExpandParent" >
            <span slot-scope="{ node, data }">
              <MenuIcon :menuType="data.type" :title="node.label" />
            </span>
          </el-tree>
        </div>
      </div>
      <div class="drawer-bootom-button">
        <el-button type="primary" icon="el-icon-check" :loading="loading" @click="handleSubmit(true)" style="margin-right: .8rem" >保存</el-button>
        <el-button type="info" icon="el-icon-close" @click="close()" :loading="loading">关闭</el-button>
      </div>
    </div>

  </el-drawer>
</template>

<script>
import {httpGet, httpPost} from '@/api';
import MenuIcon from '@/views/system/menu/MenuIcon';

export default {
  name: "roleMenu",
  components:{
    MenuIcon
  },
  data() {
    return {
      title0:"权限配置",
      title: this.title0,
      roleId:"",
      type:'',
      treeData: [],
      parentMapping:{},
      allTreeKeys: [],
      checkedKeys:[],
      expandedKeys:[],
      autoExpandParent: true,
      visible: false,
      loading: false,
      treeStyle:{
        overflow: 'auto',
        height: '820px'
      },
      url: {
        frontMenuList: '/sys/frontMenu/frontMenuList',
        admMenuList: '/sys/menu/enableList',
        roleMenulist: '/sys/roleMenu/roleMenulist',
        saveRoleMenu: '/sys/roleMenu/'
      }
    };
  },
  created() {
    window.addEventListener('resize', () => {
      this.refreshTreeHeight()
    })
  },
  mounted(){
    this.refreshTreeHeight()
  },
  methods: {
    refreshTreeHeight () {
      this.$nextTick(() => {
        this.treeStyle.height = document.body.clientHeight - 220 + 'px'
      })
    },
    loadData(){
      this.loading = true;
      let menuListUrl = this.type == 2 ? this.url.frontMenuList : this.url.admMenuList;
      Promise.all([httpGet(this.url.roleMenulist, {roleId:this.roleId, type: this.type}), httpGet(menuListUrl)]).then((res) => {
        this.checkedKeys = res[0].data;
        this.treeData = res[1].data.treeData;
        this.allTreeKeys = res[1].data.allIdList;
        if(this.checkedKeys && this.checkedKeys.length){
          this.expandedKeys = this.allTreeKeys;
        }
        this.parentMapping = {};
        this.createParentMapping(this.treeData);
      }).finally(()=>{
        this.loading = false;
      });
    },
    createParentMapping(arr){
      if(!arr || !arr.length){
        return ;
      }
      arr.forEach(item=>{
        this.parentMapping[item.id]=item.parentId;
        this.createParentMapping(item.children)
      })
    },

    handleSubmit(exit) {
      this.loading = true;
      let menuId = this.$refs.tree.getCheckedKeys().join();
      httpPost(this.url.saveRoleMenu, {
        roleId: this.roleId,
        menuId: menuId?menuId:'_NO_MENUS',
        type: this.type
      }).then(res=>{
        if(res.success){
          this.msgSuccess("保存成功！");
          if (exit) {
            this.close()
          }
        }
      }).finally(()=>{
        this.loading = false;
      });
    },

    show(roleId, type, roleName){
      this.roleId = roleId;
      this.type = type;
      this.loadData();
      this.title = this.$stringFormat('【{0}】的【{1}】权限配置', roleName, type==2?'前端':'后端');
      this.visible = true;
    },

    close () {
      this.expandedKeys = []
      this.checkedKeys = []
      this.checkAll(false);
      this.treeData = [];
      this.parentMapping = {};
      this.loading = false

      this.$emit('close');
      this.visible = false;
    },

    onCheck(node, state){
      if(state.checkedNodes.indexOf(node)>-1){
        this.setParentNodeCheck(node.parentId, true)
      }else{
        this.setSubNodeCheck(node.children, false)
      }
    },
    setParentNodeCheck(parentId, checked){
      if(!parentId){
        return;
      }
      this.$refs.tree.setChecked(parentId, checked)
      this.setParentNodeCheck(this.parentMapping[parentId], checked)
    },
    setSubNodeCheck(arr, checked){
      if(!arr || !arr.length){
        return;
      }
      arr.forEach((item)=>{
        this.$refs.tree.setChecked(item.id, checked)
        this.setSubNodeCheck(item.children, checked)
      });
    },
    checkAll (checked) {
      this.$refs.tree.setCheckedKeys(checked?this.allTreeKeys:[]);
    },
  }
};
</script>

<style scoped>
  .menu-tree{
    z-index: 10;
    border: 1px solid #91d5ff;
    border-radius: 9px;
    padding: 10px;
  }
  .el-drawer__header{
    margin-bottom: 0px !important;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: left;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
    z-index: 10;
  }

</style>
